from fastapi import FastAPI
from .api import api_router
from tortoise.contrib.fastapi import register_tortoise
from .setting.tortoise_set import TORTOISE_ORM  # 导入配置
from contextlib import asynccontextmanager
from fastapi.middleware.cors import CORSMiddleware
from fastapiApp.controllers.task_control import task_manager
from fastapiApp.utils.audit_log import audit_log_middleware
from fastapiApp.utils.global_auth import setup_global_auth
from fastapiApp.core.initapp import init_data
import asyncio

# 后台任务列表
background_tasks = []

# 应用生命周期管理
@asynccontextmanager
async def lifespan(app: FastAPI):
    await init_data()
    # 启动时自动启动所有任务
    for task_name in task_manager.tasks.keys():
        await task_manager.start_task(task_name)
    
    # 启动WebSocket状态广播任务
    from fastapiApp.api.v1.luosi_api import broadcast_state_updates
    broadcast_task = asyncio.create_task(broadcast_state_updates())
    background_tasks.append(broadcast_task)
    
    yield
    # 关闭时停止所有任务
    for task_name in task_manager.tasks.keys():
        await task_manager.stop_task(task_name)
    
    # 取消后台任务
    for task in background_tasks:
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            pass

app = FastAPI(lifespan=lifespan)

# 注册路由地址
app.include_router(api_router, prefix="/api")

# 设置全局认证，为所有v1路由添加token验证
setup_global_auth(app)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有源访问，开发环境可用
    # 生产环境建议指定具体前端域名，例如：["http://localhost:8080", "http://127.0.0.1:5173"]
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有HTTP方法
    allow_headers=["*"],  # 允许所有请求头
)

# 注册审计日志中间件
app.middleware("http")(audit_log_middleware)

# 注册 Tortoise ORM
register_tortoise(
    app,
    config=TORTOISE_ORM,
    generate_schemas=True,  # 自动生成数据库表结构（开发环境用，生产环境建议关闭）
    add_exception_handlers=True,  # 添加 Tortoise 异常处理器
)

app.title = "FastAPI 应用"
